package com.nameli.admin.service.impl.system;

import com.nameli.SIM.bean.entity.sys.SysPermission;
import com.nameli.SIM.mapper.SysPermissionMapper;
import com.nameli.SIM.util.EmptyUtil;
import com.nameli.SIM.util.UserConstants;
import com.nameli.SIM.util.routers.MetaVo;
import com.nameli.SIM.util.routers.RouterMenuUtils;
import com.nameli.SIM.util.routers.RouterNode;
import com.nameli.admin.config.SecurityTools;
import com.nameli.admin.service.SysMenuService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author NAME-L
 * @Description 权限菜单实现类
 * @className SysPermissionServiceImpl
 * @date 2022-01-10 17:17:41
 */
@Component
public class SysMenuServiceImpl implements SysMenuService {

    private static final Log logger = LogFactory.getLog(SysMenuServiceImpl.class);

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public List<SysPermission> selectMenuTreeAll() {
        return sysPermissionMapper.selectMenuTreeAll();
    }

    @Override
    public List<SysPermission> selectMenuTreeByUserId(Long userId) {
        return sysPermissionMapper.selectMenuTreeByUserId(userId);
    }

    @Override
    public List<RouterNode<SysPermission>> selectTreeAll() {
        List<SysPermission> list = sysPermissionMapper.selectMenuTreeAll();
        List<RouterNode<SysPermission>> routerNodes = RouterMenuUtils.listToTree(list, (node) -> {
            RouterNode<SysPermission> routerNode = new RouterNode<>();
            routerNode.setMenuId(node.getMenuId());
            routerNode.setParentId(node.getParentId());
            routerNode.setComponent(node.getComponent());
            routerNode.setMeta(new MetaVo(node.getMenuName() , node.getIcon()));
            routerNode.setPath(node.getPath());
            routerNode.setName(node.getPath());
            return routerNode;
        }, 0L);

        return routerNodes;
    }

    @Override
    public List<RouterNode<SysPermission>> selectTreeByUserId(Long userId) {
        List<SysPermission> list = null;
        if (SecurityTools.isAdmin(userId)){
            logger.info("当前登录用户为管理员");
            list = sysPermissionMapper.selectMenuTreeAll();
        }else {
            logger.info("当前登录用户为非管理员");
            list = sysPermissionMapper.selectMenuTreeByUserId(userId);
        }
        List<RouterNode<SysPermission>> routerNodes = RouterMenuUtils.listToTree(list, (node) -> {
            RouterNode<SysPermission> routerNode = new RouterNode<>();
            routerNode.setMenuId(node.getMenuId());
            routerNode.setParentId(node.getParentId());
            routerNode.setName(StringUtils.capitalize(node.getPath()));
            routerNode.setComponent(getComponent(node));
            routerNode.setMeta(new MetaVo(node.getMenuName() , node.getIcon()));
            routerNode.setPath(getRouterPath(node));
            routerNode.setRedirect("noRedirect");
            return routerNode;
        }, 0L);
        return routerNodes;
    }

    /**
     * 根据用户ID查询权限
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = sysPermissionMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms){
            if (EmptyUtil.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }


    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysPermission menu){
        String component = UserConstants.LAYOUT;
        if (EmptyUtil.isNotEmpty(menu.getComponent())) {
            component = menu.getComponent();
        } else if(EmptyUtil.isEmpty(menu.getComponent()) && isParentView(menu)){
            component = UserConstants.PARENT_VIEW;

        }
        return component;

    }


    /**
     * 获取路由地址
     * @param menu 才散
     * @return
     */
    public String getRouterPath(SysPermission menu){
        String routerPath = menu.getPath();
        logger.info(menu);
        // 非外链并且是一级目录（类型为目录）
        if (0L == menu.getParentId().intValue() &&
                UserConstants.TYPE_DIR.equals(menu.getMenuType()) &&
                UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
            logger.info(routerPath);
        }
//        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysPermission menu)
    {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysPermission menu)
    {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }
}
